using System.IO;
using System.Text;
using OracleInternal.Json.Common;

namespace OracleInternal.Json.Binary
{
	internal sealed class WriterJsonOutput : IJsonOutput
	{
		private char[] m_buffer = new char[4096];

		private int m_pos;

		private TextWriter m_writer;

		internal WriterJsonOutput(TextWriter writer)
		{
			m_writer = writer;
		}

		public void Close()
		{
			Flush();
			m_writer.Close();
			m_buffer = null;
		}

		public void Flush()
		{
			if (m_pos > 0)
			{
				m_writer.Write(m_buffer, 0, m_pos);
				m_pos = 0;
			}
		}

		private int EnsureCapacity(int count)
		{
			int num = m_buffer.Length - m_pos;
			if (num + count > m_buffer.Length)
			{
				Flush();
				num = m_buffer.Length;
			}
			return num;
		}

		public void WriteAscii(char[] value)
		{
			for (int i = 0; i < value.Length; i++)
			{
				if (m_pos >= m_buffer.Length)
				{
					Flush();
				}
				m_buffer[m_pos++] = value[i];
			}
		}

		public void WriteAscii(char[] value, int pos, int count)
		{
			for (int i = pos; i < pos + count; i++)
			{
				if (m_pos >= m_buffer.Length)
				{
					Flush();
				}
				m_buffer[m_pos++] = value[i];
			}
		}

		public void WriteAscii(char value)
		{
			EnsureCapacity(1);
			m_buffer[m_pos++] = value;
		}

		public void WriteAscii(byte[] value, int pos, int count)
		{
			while (count > 0)
			{
				int num = EnsureCapacity(count);
				for (int i = 0; i < num; i++)
				{
					m_buffer[m_pos++] = (char)value[pos++];
				}
				count -= num;
			}
		}

		public void WriteAscii(byte value)
		{
			EnsureCapacity(1);
			m_buffer[m_pos++] = (char)value;
		}

		public void WriteAscii(string value)
		{
			Flush();
			m_writer.Write(value);
		}

		public void WriteAscii(string value, int pos, int count)
		{
			Flush();
			m_writer.Write(value);
		}

		public void Write(char c)
		{
			EnsureCapacity(1);
			m_buffer[m_pos++] = c;
		}

		public void Write(char[] value, int pos, int count)
		{
			Flush();
			m_writer.Write(value, pos, count);
		}

		public void Write(string value)
		{
			Flush();
			m_writer.Write(value);
		}

		public void Write(string value, int pos, int count)
		{
			Flush();
			m_writer.Write(value);
		}

		public void WriteSurrogates(char c1, char c2)
		{
			Write(c1);
			Write(c2);
		}

		public bool Utf8()
		{
			return false;
		}

		public void Utf8(byte[] array, int offset, int len)
		{
			char[] chars = Encoding.UTF8.GetChars(array, offset, len);
			Flush();
			m_writer.Write(chars, 0, chars.Length);
		}
	}
}
